<?php
declare (strict_types = 1);

namespace app\admin\lib;


use think\db\exception\DbException;
use think\facade\Db;

trait Curd
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index($tableName, $key, $value)
    {
        //
        try {
            return Db::name($tableName) -> where($key, $value) -> select();
        }catch (DbException $exception){
            return $exception -> getMessage();
        }
    }

    /**
     * 增加数据
     * 显示创建资源表单页.
     * @param  int  $data
     * @return \think\Response
     */
    public function create($tableName,$data)
    {
        //
        try {
            return Db::name($tableName)->strict(false)->insert($data);
        }catch (DbException $exception){
            return $exception->getMessage();

        }
    }
    /**
     * 保存更新的资源
     *
     * @param  $tableName
     * @param  int  $id
     * @param  int  $data
     * @return \think\Response
     */
    public function update($tableName, $id, $data)
    {
        //
        try {
            return Db::name($tableName) -> where('id', $id) -> data($data) -> update();
        }catch (DbException $exception){
            return $exception -> getMessage();
        }
    }

    /**
     * 删除指定资源
     *@param  int  $tableName
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($tableName,$id)
    {
        //
        try {
            return Db::table($tableName)->where('id',$id)->delete();
        }catch (DbException $exception){
            return $exception -> getMessage();
        }
    }
    /**批量删除
     * @param $tableName
     * @param $ids
     * @return string
     */
    public function batchDelete($tableName, $ids){
        try {
            foreach ($ids as $id) {
                Db::table($tableName)->where('id',$id)->delete();
            }
        }catch (DbException $exception){
            return $exception -> getMessage();
        }
    }
}